package com.chookss.tools;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Point;
import android.os.Build;
import android.text.InputFilter;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.chookss.base.StaticClass;
import com.chookss.home.entity.UploadEntity;
import com.chookss.home.search.entity.SearchAllEntity;
import com.chookss.mine.entity.MyViedeoEntity;
import com.chookss.tiku.entity.MyExam;
import com.chookss.video.entity.VideoEntity;
import com.johnrambo.ktea.common.ToolsKt;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Company:
 * Project:
 * Author: liuhaoge
 * Date: 2021/1/27 9:01
 * Note:
 */
public class Utils {
    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static float sp2px(Context context, int spVal) {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spVal, context.getResources().getDisplayMetrics());

    }

    /**
     * 获取屏幕宽度
     */
    public static int getScreenWidthPixels(Activity context) {
        DisplayMetrics metric = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(metric);
        KLog.e("屏幕宽度getWindowManager：" + metric.widthPixels);
        return metric.widthPixels;
    }

    public static int getScreenWidthPixel(Context context) {
        Resources resources = context.getApplicationContext().getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        int width3 = dm.widthPixels;
        return width3;
    }

    public static int getDisplayHeight(Activity context) {
        //获取正确尺寸 （此方法要求最低api为17，即安卓4.2，4.2之前获取请参看以下获取屏幕尺寸的方法）
        //此种必须在继承了window的布局中获取才能得到值
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            Point point = new Point();
            WindowManager windowManager = context.getWindowManager();
            windowManager.getDefaultDisplay().getSize(point);
            windowManager.getDefaultDisplay().getRealSize(point);
            KLog.e("屏幕真实宽高w：" + point.x + " h:" + point.y);
            return point.y;
        } else {
            //无刘海屏及导航栏手机，直接获取高度
            DisplayMetrics metric = context.getResources().getDisplayMetrics();
            KLog.e("屏幕宽高w：" + metric.heightPixels + " h:" + metric.widthPixels);
            return metric.heightPixels;
        }
    }

    public static int getScreenHeight(Context context) {
        return context.getResources().getDisplayMetrics().heightPixels;
    }

    public static int getStatusBarHeight(Context mContext) {
        // 获取状态栏高度
        int statusBarHeight = dip2px(mContext, 20);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            //根据屏幕宽高计算高度
            int resourceId = mContext.getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                statusBarHeight = mContext.getResources().getDimensionPixelSize(resourceId);
            }
//            KLog.e("状态栏resourceId："+resourceId+ "  高度："+statusBarHeight);
        }
        return statusBarHeight;
    }

    public static int getStatusBarHeightDp(Context mContext) {
        // 获取状态栏高度
        int statusBarHeight = dip2px(mContext, 20);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            //根据屏幕宽高计算高度
            int resourceId = mContext.getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                statusBarHeight = mContext.getResources().getDimensionPixelSize(resourceId);
            }
            KLog.e("状态栏resourceId：" + resourceId + "  高度：" + statusBarHeight);
        }
        return px2dip(mContext, statusBarHeight);
    }

    /**
     * 获取当前app版本号
     */
    public static String getVersionName(Context context) {
        String versionName = "1.0.1";
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        try {
            PackageManager packageManager = context.getApplicationContext().getPackageManager();
            PackageInfo packInfo;
            packInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            versionName = packInfo.versionName;
        } catch (Exception e) {
            e.printStackTrace();
            return versionName;
        }
        return versionName;
    }

    /**
     * 获取当前app版本号
     */
    public static int getVersionCode(Context context) {
        int versionCode = 0;
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packInfo = null;
        try {
            packInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        versionCode = packInfo.versionCode;
        return versionCode;
    }

    public static VideoEntity modelA2B(MyViedeoEntity.VideoListBean item) {
        try {
            VideoEntity video = new VideoEntity();
            video.id = item.getId();
            video.companyCode = item.getCompanyCode();
            video.employeeCode = item.getEmployeeCode();
            video.employeeName = item.getEmployeeName();
            video.employeeId = item.getEmployeeId();
            video.headPhotoUrl = item.getHeadPhotoUrl();
            video.headPhotoThumbUrl = item.getHeadPhotoThumbUrl();
            video.videoTitle = item.getVideoTitle();
            video.videoId = item.getVideoId();
            video.videoCoverPath = item.getVideoCoverPath();
            video.videoCollectionsCode = item.getVideoCollectionsCode();
            video.videoCollectionsName = item.getVideoCollectionsName();
            video.videoLikeCounts = item.getVideoLikeCounts();
            video.videoShareCounts = item.getVideoShareCounts();
            video.videoCollectCounts = item.getVideoCollectCounts();
            video.videoCommentCounts = item.getVideoCommentCounts();
            video.catalogCodes = item.getCompanyCode();
            video.catalogNames = item.getCatalogNames();
            video.isLike = item.getIsLike();
            video.isCollect = item.getIsCollect();
            video.courseCode = item.getCourseCode();
            video.videoType = item.getCourseCode();
            video.youIsfans = item.getYouIsfans();
            video.isYoufans = item.getIsYoufans();
            video.videoType = item.getVideoType();
            video.videoSeconds = item.getVideoSeconds();
            video.isShare = item.getIsShare();
            video.videoPlayCounts = "0";
            video.isTask = "0";
            video.isSingle = item.getIsSingle();
            return video;
        } catch (Exception e) {
            return null;
        }
    }

    public static UploadEntity.VideoBean modelA2BUploadVideo(MyViedeoEntity.VideoListBean item) {
        try {
            UploadEntity.VideoBean video = new UploadEntity.VideoBean();
            video.setId(item.getId());
            video.setCompanyCode(item.getCompanyCode());
            video.setEmployeeCode(item.getEmployeeCode());
            video.setProvideEmployeeName(item.getEmployeeName());
            video.setProvideEmployeeCode(item.getEmployeeCode());
            video.setEmployeeCode(item.getEmployeeId());
            video.setVideoTitle(item.getVideoTitle());
            video.setVideoId(item.getVideoId());
            video.setVideoCoverPath(item.getVideoCoverPath());
            video.setVideoCollectionsCode(item.getVideoCollectionsCode());
            video.setVideoCollectionsName(item.getVideoCollectionsName());
            video.setVideoLikeCounts(item.getVideoLikeCounts());
            video.setVideoShareCounts(item.getVideoShareCounts());
            video.setVideoCollectCounts(item.getVideoCollectCounts());
            video.setVideoCommentCounts(item.getVideoCommentCounts());
            video.setCompanyCode(item.getCompanyCode());
            video.setCatalogNames(item.getCatalogNames());
            video.setCatalogCodes(item.getCatalogCodes());
            video.setShareFlag(item.getIsShare());
            video.setVideoKeyWord(item.getVideoKeyWord());
            video.setVideoLocation(item.getVideoLocation());
            video.setVideoOpenStatus(item.getVideoOpenStatus());
            video.setShareFlag(item.getShareFlag());
            video.setOriginal(item.getOriginal());
            video.setFileUrl(item.getFileUrl());
            return video;
        } catch (Exception e) {
            return null;
        }
    }

    public static MyExam modelA2B(SearchAllEntity.ExamBean.ListBean item) {
        try {
            MyExam myExam = new MyExam();
            myExam.examCode = item.getExamCode();
            myExam.examName = item.getExamName();
            myExam.examTimeLength = item.getExamTimeLength();
            myExam.examDetail = item.getExamDetail();
            myExam.startTime = item.getStartTime();
            myExam.endTime = item.getEndTime();
            myExam.score = item.getScore();
            myExam.seconds = item.getSeconds();
            myExam.examStatus = item.getExamStatus();
            myExam.recordUid = item.getRecordUid();
            myExam.createTime = item.getCreateTime();
            return myExam;
        } catch (Exception e) {
            return null;
        }
    }

    //转换分钟 小时 刚刚  显示时间的时候用
    public static String getAccurateDate(String data) {
        //传值 2018-10-10 10:20:13
        if (isNull(data)) {
            return "";
        }
        if (data.length() <= 10) {
            return data;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String nowDate = "";
        String newData = "";
        Long now = null;
        try {
            nowDate = sdf.format(new Date());
            if (data.length() > 19) {
                newData = data.substring(0, 19);
            } else {
                newData = data;
            }
            now = System.currentTimeMillis() - sdf.parse(newData).getTime();
            Calendar today_cal = Calendar.getInstance();
            Calendar old_cal = Calendar.getInstance();
            today_cal.setTime(sdf.parse(nowDate));
            old_cal.setTime(sdf.parse(newData));
            if (!isNull(nowDate) && !isNull(newData)) {
                if (today_cal.get(Calendar.YEAR) == old_cal.get(Calendar.YEAR)) {
                    //相同年份
                    if (today_cal.get(Calendar.DAY_OF_YEAR) == old_cal.get(Calendar.DAY_OF_YEAR)) {
                        //当天
                        if (now / 1000 / 60 < 1) {
                            //1分钟以内
                            nowDate = "刚刚";
                        } else if (now / 1000 / 60 / 60 < 1) {
                            //60分钟以内
                            nowDate = (int) (now / 1000 / 60) + "分钟前";
                        } else {
                            //24小时以内
                            nowDate = (int) (now / 1000 / 60 / 60) + "小时前";
                        }
                    } else if ((today_cal.get(Calendar.DAY_OF_YEAR) - old_cal.get(Calendar.DAY_OF_YEAR)) == 1) {
                        //昨天
                        nowDate = "昨天";
                    } else {
                        //昨天之前，但是是今年的显示09-30
                        nowDate = newData.substring(5, 10);
                    }
                } else {
                    //不同年份2020-09-30
                    if (newData.length() > 10) {
                        nowDate = newData.substring(0, 10);
                    }
                }
            }

        } catch (java.text.ParseException e) {
            e.printStackTrace();
            return nowDate;
        }

        return nowDate;
    }

    //传值 2018-10-10 10:20:13 取日期区间
    public static String getTimeSize(String data, int start, int end) {
        String nowDate = "";
        try {
            if (isNull(data)) {
                return nowDate;
            } else if (data.length() >= end) {
                nowDate = data.substring(start, end);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return nowDate;
    }

    public static String getCurrentTime() {
        String nowDate = "";
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM月dd日 HH:mm");
        nowDate = dateFormat.format(date);
        return nowDate;
    }

    public static String getCurrentTime2() {
        String nowDate = "";
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        nowDate = dateFormat.format(date);
        return nowDate;
    }

    public static String getAddressLoc(String jwd) {
        String addressLoc = "";
        if (isNull(jwd)) {
            return jwd;
        } else {
            String[] addressLocs = jwd.split("\\.");
            if (addressLocs.length > 1) {
                if (addressLocs[1].length() > 6) {
                    addressLoc = addressLocs[0] + "." + addressLocs[1].substring(0, 6);
                } else {
                    addressLoc = jwd;
                }
            } else {
                addressLoc = jwd;
            }
        }
        return addressLoc;
    }

    public static String getCurrentTime3() {
        String nowDate = "";
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        nowDate = dateFormat.format(date);
        return nowDate;
    }

    //获取当前时间
    public static String getCurrentTime(int type) {
        //传值 2018-10-10 10:20:13

        String nowDate = "";

        try {
            Date date = new Date();
            SimpleDateFormat dateFormat;
            if (type == 3) {
                dateFormat = new SimpleDateFormat("MM月dd日 HH:mm");
                nowDate = dateFormat.format(date) + "的日志";
            } else if (type == 0) {
                dateFormat = new SimpleDateFormat("MM月dd日");
                nowDate = dateFormat.format(date) + "的日报";
            } else if (type == 1) {
                Calendar cal = Calendar.getInstance();//这一句必须要设置，否则美国认为第一天是周日，而我国认为是周一，对计算当期日期是第几周会有错误
                cal.setFirstDayOfWeek(Calendar.MONDAY); // 设置每周的第一天为星期一
//                cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);// 每周从周一开始
//                cal.setMinimalDaysInFirstWeek(7); // 设置每周最少为7天
                cal.setTime(new Date());
                if (cal.get(Calendar.WEEK_OF_YEAR) == 1 && cal.get(Calendar.MONTH) == 11) {
                    nowDate = "的" + addNumber(cal.get(Calendar.YEAR) + "") + "年第" + cal.get(Calendar.WEEK_OF_YEAR) + "周周报";
                } else {
                    nowDate = "的第" + cal.get(Calendar.WEEK_OF_YEAR) + "周周报";
                }
            } else if (type == 2) {
                dateFormat = new SimpleDateFormat("MM月dd日");
                String month = dateFormat.format(date).split("月")[0];
                if (month.startsWith("0")) {
                    month = month.substring(1, 2);
                }
                nowDate = "的第" + month + "月月报";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return nowDate;
    }

    //获取当前时间
    public static String getCurrentDay(String type, String time) {
        //传值 2018-10-10 10:20:13
        String nowDate = "";
        try {
            if (!isNull(time)) {
                if (time.length() > 10) {
                    String[] newTime = time.substring(0, 10).split("-");
                    if (newTime.length >= 2) {
                        nowDate = newTime[1] + "月" + newTime[2] + "日";
                    }

                }
                if ("3".equals(type)) {

                    if (time.length() > 16) {
                        String hours = time.substring(11, 16);
                        return nowDate + " " + hours + "的日志";
                    }
                } else if ("0".equals(type)) {
                    return nowDate + "的日报";
                } else if ("1".equals(type)) {
                    Calendar cal = Calendar.getInstance();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    Calendar calendar = Calendar.getInstance();
                    calendar.setFirstDayOfWeek(Calendar.MONDAY);
                    Date date = null;
                    try {
                        date = sdf.parse(time);
                        cal.setFirstDayOfWeek(Calendar.MONDAY); // 设置每周的第一天为星期一
//                        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);// 每周从周一开始
//                        cal.setMinimalDaysInFirstWeek(7); // 设置每周最少为7天
                        cal.setTime(date);
                        if (cal.get(Calendar.WEEK_OF_YEAR) == 1 && time.substring(5, 7).equals("12")) {
                            return "的" + addNumber(time.substring(0, 4)) + "年第" + cal.get(Calendar.WEEK_OF_YEAR) + "周周报";
                        } else {
                            return "的第" + cal.get(Calendar.WEEK_OF_YEAR) + "周周报";
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                } else if ("2".equals(type)) {
                    String month = time.substring(5, 7);
                    if (month.startsWith("0")) {
                        month = month.substring(1, 2);
                    }
                    return "的第" + month + "月月报";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return nowDate;
    }

    //转换只要年月或者年
    public static String getAccurateDate2(String data, int startNum, int endNum) {
        //传值 2018-10-10 10:20:13
        String nowDate = "";
        try {
            if (isNull(data)) {
                return "";
            }
            if (data.length() >= endNum) {
                nowDate = data.substring(startNum, endNum);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return nowDate;
    }

    /**
     * 判断2个时间大小
     * yyyy-MM-dd HH:mm 格式（自己可以修改成想要的时间格式）
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public static int getTimeCompareSize(String startTime, String endTime) {
        int i = 0;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");//年-月-日 时-分
        try {
            Date date1 = dateFormat.parse(startTime);//开始时间
            Date date2 = dateFormat.parse(endTime);//结束时间
            // 1 结束时间小于开始时间 2 开始时间与结束时间相同 3 结束时间大于开始时间
            if (date2.getTime() < date1.getTime()) {
                i = 1;
            } else if (date2.getTime() == date1.getTime()) {
                i = 2;
            } else if (date2.getTime() > date1.getTime()) {
                //正常情况下的逻辑操作.
                i = 3;
            }
        } catch (ParseException e) {
            e.printStackTrace();
            return i;
        }
        return i;
    }

    /**
     * 判断2个时间大小
     * yyyy-MM-dd HH:mm 格式（自己可以修改成想要的时间格式）
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public static int getTimeCompareSize(String currentTime, String startTime, String endTime) {
        int i = 0;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");//年-月-日 时-分
        try {
            Date date0 = dateFormat.parse(currentTime);//开始时间
            Date date1 = dateFormat.parse(startTime);//开始时间
            Date date2 = dateFormat.parse(endTime);//结束时间
            if (date0.getTime() < date1.getTime()) {
                //未开始
                i = 3;
            } else if (date0.getTime() > date2.getTime()) {
                //已结束
                i = 1;
            } else {
//                 进行中
                i = 2;
            }
        } catch (ParseException e) {
            e.printStackTrace();
            return i;
        }
        return i;
    }

    /**
     * 判断2个时间大小
     * yyyy-MM-dd HH:mm 格式（自己可以修改成想要的时间格式）
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public static int getMonthCompareSize(String startTime, String endTime) {
        int i = 0;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");//年-月-日 时-分
        try {
            Date date1 = dateFormat.parse(startTime);//开始时间
            Date date2 = dateFormat.parse(endTime);//结束时间
            // 1 结束时间小于开始时间 2 开始时间与结束时间相同 3 结束时间大于开始时间
            if (date2.getTime() < date1.getTime()) {
                i = 1;
            } else if (date2.getTime() == date1.getTime()) {
                i = 2;
            } else if (date2.getTime() > date1.getTime()) {
                //正常情况下的逻辑操作.
                i = 3;
            }
        } catch (ParseException e) {
            e.printStackTrace();
            return i;
        }
        return i;
    }

    /**
     * 判断2个时间大小
     * yyyy-MM-dd HH:mm 格式（自己可以修改成想要的时间格式）
     *
     * @return
     */
    public static String getTimeCompareSize2(String planStatus, String current, String start, String end) {
        String time = current;
        try {
            if ("3".equals(planStatus)) {
                //已经结束
                time = end.substring(0, 10);
            } else if ("1".equals(planStatus)) {
                //未开始
                time = start.substring(0, 10);
            } else if ("2".equals(planStatus)) {
                //当前时间是 计划中
                time = current;
            }
        } catch (Exception e) {
            e.printStackTrace();
            time = current;
        }
        return time;
    }

    /**
     * 判断2个时间大小
     * yyyy-MM-dd HH:mm 格式（自己可以修改成想要的时间格式）
     *
     * @return
     */
    public static String getMonthCompareSize2(String planStatus, String current, String start, String end) {

        String time = current;
        try {
            //1未开始2进行中3已结束
            if ("3".equals(planStatus)) {
                //已经结束
                time = end.substring(0, 7);
            } else if ("1".equals(planStatus)) {
                //未开始
                time = start.substring(0, 7);
            } else if ("2".equals(planStatus)) {
                //当前时间是 计划中
                time = current;
            }
        } catch (Exception e) {
            e.printStackTrace();
            time = current;
        }
        return time;
    }


    //
    public static List<String> getMonths(String startTime, String endTime) {
        DateFormat formater = new SimpleDateFormat("yyyy-MM");
        Calendar beginCalendar = Calendar.getInstance();
        Calendar finishCalendar = Calendar.getInstance();
        try {
            beginCalendar.setTime(formater.parse(startTime));
            finishCalendar.setTime(formater.parse(endTime));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        List<String> time = new ArrayList<>();
        while (beginCalendar.before(finishCalendar)) {
            String date = formater.format(beginCalendar.getTime()).toUpperCase();
            time.add(date);
            beginCalendar.add(Calendar.MONTH, 1);
        }
        time.add(formater.format(finishCalendar.getTime()).toUpperCase());
        return time;
    }

    //
    public static List<String> getYears(String startTime, String endTime) {
        DateFormat formater = new SimpleDateFormat("yyyy");
        Calendar beginCalendar = Calendar.getInstance();
        Calendar finishCalendar = Calendar.getInstance();
        try {
            beginCalendar.setTime(formater.parse(startTime));
            finishCalendar.setTime(formater.parse(endTime));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        List<String> time = new ArrayList<>();
        while (beginCalendar.before(finishCalendar)) {
            String date = formater.format(beginCalendar.getTime()).toUpperCase();
            time.add(date);
            beginCalendar.add(Calendar.YEAR, 1);
        }
        time.add(formater.format(finishCalendar.getTime()).toUpperCase());
        return time;
    }

    /**
     * @param time 清除后台返回的时间格式多余的0
     */
    public static String clearZeroTime(String time) {
        String newTime = null;
        try {
            newTime = "";
            if (isNull(time)) {
                return newTime;
            }
            if (time.length() > 19) {
                newTime = time.substring(0, 19);
            } else {
                newTime = time;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return newTime;
    }

    /**
     * @param time 清除后台返回的时间格式多余的0
     */
    public static String clearZeroDay(String time) {
        String newTime = null;
        try {
            newTime = "";
            if (isNull(time)) {
                return newTime;
            }
            if (time.length() > 10) {
                newTime = time.substring(0, 10);
            } else {
                newTime = time;
            }
            newTime = getNormalYMDTime(newTime);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return newTime;
    }

    /**
     * @param time 清除后台返回的时间格式多余的0
     */
    public static String clearZeroTimes(String time) {
        String newTime = "";
        try {
            if (isNull(time)) {
                return newTime;
            }
            if (time.length() > 16) {
                newTime = time.substring(0, 16);
            } else {
                newTime = time;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return newTime;
    }

    //转换KB  MB  GB
    public static String changeKM(String data) {
        String newData = "";
        try {
            if (TextUtils.isEmpty(data)) {
                return "";
            }
            if (data.contains("K") || data.contains("M") || data.contains("G") || data.contains("B")) {
                return data;
            }
            float dataFloat = Integer.parseInt(data);
            if (dataFloat <= 1024) {
                newData = data + "B";
            } else if (dataFloat > 1024 && dataFloat <= 1048576) {
                newData = keepDecimal(dataFloat / 1024 + "") + "KB";
            } else if (dataFloat > 1048576 && dataFloat <= 1073741824) {
                newData = keepDecimal(dataFloat / 1048576 + "") + "MB";
            } else if (dataFloat > 1073741824) {
                newData = keepDecimal(dataFloat / 1073741824 + "") + "GB";
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return "";
        }
        return newData;
    }
    //转换为w
    /**
     * @param data 单位换算 10000以下展示精确 10000以上展示w
     * @return
     */
    public static String changeW(String data) {
        String time = null;
        try {
            if (isNull(data)) {
                time = "0";
            } else {
                float num = Float.parseFloat(data);
                if (num < 10000) {
                    time = data+"";
                } else {
                    time = keepDecimal2(num / 10000 + "");
//                    time = keepDecimal(num / 10000 + "") + "w";
                }

            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return data;
        }
        return time;
    }

    //转换为带一位的小数

    public static String keepDecimal(String data) {
        String newData = "";
        if (TextUtils.isEmpty(data)) {
            return "";
        }
        try {
            if (data.split("\\.").length > 1) {
                String xiaoshu = data.split("\\.")[1];
                if ("0".equals(xiaoshu.substring(0, 1))) {
                    newData = data.split("\\.")[0];
                } else {
                    newData = data.split("\\.")[0] + "." + xiaoshu.substring(0, 1);
                }

            } else {
                return data;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return newData;
    }
    public static String keepDecimal2(String data) {
        String newData = "";
        if (TextUtils.isEmpty(data)) {
            return "";
        }
        try {
            if (data.split("\\.").length > 1) {
                String xiaoshu = data.split("\\.")[1];
                if(xiaoshu.length()>1){
                    if ("00".equals(xiaoshu.substring(0, 2))) {
                        newData = data.split("\\.")[0];
                    } else {
                        newData = data.split("\\.")[0] + "." + xiaoshu.substring(0, 2);
                    }
                }else{
                    if ("0".equals(xiaoshu)) {
                        newData = data.split("\\.")[0];
                    } else {
                        newData = data.split("\\.")[0] + "." + xiaoshu.substring(0, 1);
                    }
                }


            } else {
                return data;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return newData;
    }
    /**
     * @param num 数字加1
     * @return
     */
    public static String addNumber(String num) {
        String number = "";
        try {
            if (isNull(num)) {
                number = "0";
            } else {
                int numInt = Integer.parseInt(num) + 1;
                if (numInt < 0) {
                    numInt = 0;
                }
                number = numInt + "";
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return "";
        }
        return number;
    }

    /**
     * @param num 数字-1
     * @return
     */
    public static String subtractionNumber(String num) {
        String number = "";
        try {
            if (isNull(num)) {
                number = "0";
            } else {
                int numInt = Integer.parseInt(num) - 1;
                if (numInt < 0) {
                    numInt = 0;
                }
                number = numInt + "";
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return "";
        }
        return number;
    }

    /**
     * @param num 数字
     * @return
     */
    public static int changeNumber(String num) {
        int number;
        int numInt = 0;
        try {
            if (isNull(num)) {
                number = 0;
            } else {
                if (num.contains(".")) {
                    numInt = Integer.parseInt(num.split("\\.")[0]);
                } else {
                    numInt = Integer.parseInt(num);
                }
                if (numInt < 0) {
                    numInt = 0;
                }
                number = numInt;
            }
        } catch (NumberFormatException e) {
            number = 0;
            e.printStackTrace();
        }
        return number;
    }

    /**
     * @param num 数字
     * @return
     */
    public static float changeFloat(String num) {
        float number;
        if (isNull(num)) {
            number = 0;
        } else {
            number = Float.parseFloat(num);
        }

        return number;
    }

    /**
     * @return
     * @param秒转为 00:00
     */
    public static String changeSeconds(int mCount) {
        String data = "";
        try {
            if (mCount < 60) {
                if (mCount < 10) {
                    data = "00:0" + mCount;
                } else {
                    data = "00:" + mCount;
                }
            } else {
                int minutes = mCount / 60;
                int seconds = mCount % 60;
                if (minutes < 10) {
                    if (seconds < 10) {
                        data = "0" + minutes + ":0" + seconds;
                    } else {
                        data = "0" + minutes + ":" + seconds;
                    }
                } else {
                    if (seconds < 10) {
                        data = minutes + ":0" + seconds;
                    } else {
                        data = minutes + ":" + seconds;
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return data;
    }

    /**
     * @param num 返回的时间是秒，转换给正式格式
     * @return
     */
    public static String changeTime(String num) {
        String time = null;
        try {
            if (isNull(num)) {
                time = "00:00";
            } else {
                int numInt = Integer.parseInt(num);
                int secondInt, minute, hours;
                String seconds;
                if (numInt < 60) {
                    if (numInt < 10) {
                        time = "00:0" + numInt;
                    } else {
                        time = "00:" + numInt;
                    }

                } else if (numInt >= 60 && numInt < 3600) {
                    minute = numInt / 60;
                    secondInt = numInt % 60;
                    if (secondInt < 10) {
                        seconds = "0" + secondInt;
                    } else {
                        seconds = secondInt + "";
                    }
                    if (minute < 10) {
                        time = "0" + minute + ":" + seconds;
                    } else {
                        time = minute + ":" + seconds;
                    }

                } else if (numInt >= 3600) {
                    hours = numInt / 3600;
                    minute = numInt / 60 % 60;
                    secondInt = numInt % 60;
                    if (secondInt < 10) {
                        seconds = "0" + secondInt;
                    } else {
                        seconds = secondInt + "";
                    }
                    if (minute < 10) {
                        time = hours + ":" + "0" + minute + ":" + seconds;
                    } else {
                        time = hours + ":" + minute + ":" + seconds;
                    }

                }
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return "";
        }
        return time;
    }

    /**
     * @param num 单位换算 1万以下展示精确 1万以上展示万
     * @return
     */
    public static String changeCounts(String num) {
        String time = null;
        try {
            if (isNull(num)) {
                time = "0";
            } else {
                int numInt = Integer.parseInt(num);
                if (numInt < 10000) {
                    time = num;
                } else {
                    float numFloat = (float) numInt / 10000;
                    time = keepDecimal(numFloat + "") + "万";
                }

            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return "";
        }
        return time;
    }

    /**
     * @param num 单位换算 1万以下展示精确 1万以上展示万
     * @return
     */
    public static String changeCounts2(String num) {
        String time = null;
        try {
            if (isNull(num)) {
                time = "0";
            } else {
                int numInt = Integer.parseInt(num);
                if (numInt < 10000) {
                    time = num;
                } else {
                    float numFloat = (float) numInt / 10000;
                    time = keepDecimal(numFloat + "") + "w";
                }

            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return "";
        }
        return time;
    }

    /**
     * @param distance 单位换算 1000以下展示精确 1000以上展示km
     * @return
     */
    public static String changeDistance(String distance) {
        String time = null;
        try {
            if (isNull(distance)) {
                time = "0m";
            } else {
                int numInt = Integer.parseInt(ClearMoreZeroUtil.subZeroAndDot(distance));
                if (numInt < 1000) {
                    time = numInt + "m";
                } else {
                    float numFloat = (float) numInt / 1000;
                    time = keepDecimal(numFloat + "") + "km";
                }

            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return distance + "m";
        }
        return time;
    }

    /**
     * @param data 2021-09-23 转成 2021年09月23日
     * @return
     */
    public static String getNormalYMDTime(String data) {
        String time = "";
        try {
            if (!Utils.isNull(data)) {
                String[] times = data.split("-");
                for (int i = 0; i < times.length; i++) {
                    if (i == 0) {
                        time = times[0] + "年";
                    } else if (i == 1) {
                        time = time + times[1] + "月";
                    } else if (i == 2) {
                        time = time + times[2] + "日";
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return time;
    }

    /**
     * @param data 秒数转换时间
     * @return
     */
    public static String getExamTime(String data) {
        String time = "0";
        try {
            if (!Utils.isNull(data)) {
                int seconds = changeNumber(data);
                if (seconds < 3600) {
                    time = seconds + "秒";
                } else if (seconds >= 3600 && seconds < 3600 * 24) {
                    if (seconds == 3600) {
                        time = "1小时";
                    } else {
                        time = seconds / 3600 + "小时";
                    }
                } else if (seconds == 3600 * 24) {
                    time = "1天";
                } else {
                    time = seconds / 3600 / 24 + "天";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return time;
    }

    /**
     * @param color   关键字变色
     * @param text
     * @param keyword
     * @return
     */
    public static SpannableString matcherSearchTitle(int color, String text, String keyword) {
        String string = text.toLowerCase();
        String key = keyword.toLowerCase();

        Pattern pattern = Pattern.compile(key);
        Matcher matcher = pattern.matcher(string);

        SpannableString ss = new SpannableString(text);
        while (matcher.find()) {
            int start = matcher.start();
            int end = matcher.end();
            ss.setSpan(new ForegroundColorSpan(color), start, end,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return ss;
    }

    /**
     * @param color   关键字变色
     * @param text
     * @param keyword
     * @return
     */
    public static SpannableString matcherSearchTitle2(int color, String text, String noColor, String keyword) {
        String string = text.toLowerCase();
        String key = keyword.toLowerCase();

        Pattern pattern = Pattern.compile(key);
        Matcher matcher = pattern.matcher(string);

        SpannableString ss = new SpannableString(text);
        while (matcher.find()) {
            int start = matcher.start();
            int end = matcher.end();
            ss.setSpan(new ForegroundColorSpan(color), start, end,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        return ss;
    }

    //判断是否为空  分钟变时间
    public static String secondChangeMinute(String data) {
        String time = "30";
        String minute = "", hours = "";
        try {
            if (!isNull(data)) {
                int timeInt = Integer.parseInt(data);
                if (timeInt < 60) {
                    time = data + "分钟";
                } else if (timeInt >= 60 && timeInt < 1440) {
                    int hoursInt = timeInt / 60;
                    int minuteInt = timeInt % 60;
                    if (minuteInt == 0) {
                        time = hoursInt + "小时";
                    } else {
                        time = hoursInt + "小时" + minuteInt + "分钟";
                    }
                } else if (timeInt >= 1440) {
                    int dayInt = timeInt / 1440;
                    int hoursInt = timeInt % 1440 % 60;
                    int minuteInt = timeInt % 60;
                    if (hoursInt == 0) {
                        hours = "";
                    } else {
                        hours = hoursInt + "小时";
                    }
                    if (minuteInt == 0) {
                        minute = "";
                    } else {
                        minute = minuteInt + "分钟";
                    }
                    time = dayInt + "天" + hours + minute;
                }
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return "";
        }
        return time;
    }

    //判断是否为空   秒变时间
    public static String secondChangeTime(String data) {
        String time = "";
        int secondInt = 0, hoursInt = 0, minuteInt = 0, dayInt = 0;
        try {
            if (!isNull(data)) {
                int timeInt = Integer.parseInt(data);
                if (timeInt < 60) {
                    time = data + "秒";
                } else if (timeInt >= 60 && timeInt < 3600) {
                    minuteInt = timeInt / 60;
                    secondInt = timeInt % 60;
                    if (secondInt == 0) {
                        time = minuteInt + "分钟";
                    } else {
                        time = minuteInt + "分钟" + secondInt + "秒";
                    }
                } else if (timeInt >= 3600 && timeInt < 86400) {
                    hoursInt = timeInt / 3600;
                    minuteInt = timeInt % 3600 / 60;
                    if (minuteInt == 0) {
                        time = hoursInt + "小时";
                    } else {
                        time = hoursInt + "小时" + minuteInt + "分钟";
                    }
                } else if (timeInt >= 86400) {
                    dayInt = timeInt / 86400;
                    hoursInt = timeInt % 86400 / 3600;
                    if (hoursInt == 0) {
                        time = dayInt + "天";
                    } else {
                        time = dayInt + "天" + hoursInt + "小时";
                    }
                }
            }
            return time;
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return "";
        }
    }

    public static String changeCnDate(String time) {
        String date = "";
        try {
            if (time.length() < 5) {
                date = time + "年";
            } else if (time.length() < 8) {
                date = time.substring(0, 4) + "年" + time.substring(5, 7) + "月";
            } else if (time.length() >= 10) {
                date = time.substring(0, 4) + "年" + time.substring(5, 7) + "月" + time.substring(8, 10) + "日";
            } else {
                date = time;
            }
        } catch (Exception e) {
            e.printStackTrace();
            date = time;
        }
        return date;
    }

    /**
     * @return
     */
    public static String addDate() {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DAY_OF_MONTH, 5);
        return sf.format(c.getTime());
    }

    public static String changeWeek(String time) {
        //2021-10-35
        String week = "";
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        Date date = null;
        try {
            date = sdf.parse(time);
            cal.setFirstDayOfWeek(Calendar.MONDAY); // 设置每周的第一天为星期一
//            cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);// 每周从周一开始
//            cal.setMinimalDaysInFirstWeek(7); // 设置每周最少为7天
            cal.setTime(date);
            if (cal.get(Calendar.WEEK_OF_YEAR) == 1 && time.substring(5, 7).equals("12")) {
                week = addNumber(time.substring(0, 4)) + "年第" + cal.get(Calendar.WEEK_OF_YEAR) + "周";
            } else {
                week = time.substring(0, 4) + "年第" + cal.get(Calendar.WEEK_OF_YEAR) + "周";
            }
        } catch (ParseException e) {
            e.printStackTrace();
            week = time;
        }

        return week;
    }

    public static int getCurrentWeek(String time) {
        //2021-10-35
        int week = 1;
        Date date = null;
        try {
            Calendar cal = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            cal.setFirstDayOfWeek(Calendar.MONDAY); // 设置每周的第一天为星期一
//            cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);// 每周从周一开始
//            cal.setMinimalDaysInFirstWeek(7); // 设置每周最少为7天
            if (isNull(time)) {
                cal.setTime(new Date());
            } else {
                date = sdf.parse(time);
                cal.setTime(date);
            }
            week = cal.get(Calendar.WEEK_OF_YEAR);
        } catch (Exception e) {
            e.printStackTrace();
            week = 1;
        }
        return week;
    }

    //计算日期差
    public static int daysBetween(String smdate, String bdate) {
        int day = 1;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        try {
            cal.setTime(sdf.parse(smdate));
            long time1 = cal.getTimeInMillis();
            cal.setTime(sdf.parse(bdate));
            long time2 = cal.getTimeInMillis();
            long between_days = (time2 - time1) / (1000 * 3600 * 24);
            day = Integer.parseInt(String.valueOf(between_days));
        } catch (ParseException e) {
            e.printStackTrace();
            day = 1;
        }
        return day;
    }

    public static String getCacheName(Context context, String key) {
        String newKey = "";
        String employeecode = new ShareUtils().getString(context, StaticClass.EMPLOYEECODE, "");
        return employeecode + "_" + key;
    }

    /**
     * 网络返回错误时候 @param String
     */

    public static String onErrorTips(String message) {
        String error = "";
        if (ToolsKt.isEmpty(message)) {
            return error;
        } else if (message.contains("Failed to") || message.contains("resolve host")) {
            return "网络异常，请检查网络重试";
        } else if (message.contains("BEGIN_OBJECT") || message.contains("IllegalStateException") || message.contains("4") || message.contains("5") || message.contains("failed")) {
            return "服务器异常，请稍后重试";
        } else if (message.contains("but") || message.contains("http")) {
            return "服务器异常，请稍后重试";
        } else {
            return message;
        }
    }

    //判断是否为空
    public static boolean isNull(String data) {
        return TextUtils.isEmpty(data) || "null".equals(data);
    }

    /**
     * 获取手机型号
     *
     * @return 手机型号
     */
    public static String getSystemModel() {
        return android.os.Build.MODEL;
    }

    /**
     * 隐藏键盘
     */
    public static void hideInputKeyboard(Context context, View v) {
        try {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void showSoftInputFromWindow(Activity context, View editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        InputMethodManager inputManager =
                (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(editText, 0);
    }

    /**
     * 禁止EditText输入特殊字符
     *
     * @param editText EditText输入框
     */
    public static void setEditTextInputSpeChat(EditText editText) {
        InputFilter inputFilter = new InputFilter() {

            Pattern pattern = Pattern.compile("[^a-zA-Z0-9\\u4E00-\\u9FA5_]");

            @Override
            public CharSequence filter(CharSequence charSequence, int i, int i1, Spanned spanned, int i2, int i3) {
                Matcher matcher = pattern.matcher(charSequence);
                if (!matcher.find()) {
                    return null;
                } else {
                    MyToast.show("只能输入汉字,英文,数字");
                    return "";
                }

            }
        };
        editText.setFilters(new InputFilter[]{inputFilter});
    }

    /**
     * 是否使屏幕常亮
     *
     * @param activity
     */
    public static void keepScreenLongLight(Activity activity, boolean isOpenLight) {
        Window window = activity.getWindow();
        if (isOpenLight) {
            window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        } else {
            window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }

    }
}